﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using DreamSpace.Net.Utilities;
using DreamSpace.Net.ScriptEngines;
using V8.Net;

namespace DreamSpace.Net
{
    // ########################################################################################################################

    public enum MessageType { CallFunction, SendMessage };

    // ########################################################################################################################

    [ScriptObject]
    public class Message
    {
        public readonly MessageType MessageType;
        public readonly object[] Data;
        public Message(MessageType type, object[] data) { MessageType = type; Data = data; }
    };

    // ########################################################################################################################

    public partial interface IServerHost<out TScriptEngine> where TScriptEngine : class, IScriptEngine
    {
        DreamSpaceServer DreamSpaceServer { get; }

        IScriptEngine ScriptEngine { get; }

        Dictionary<string, Thread> Threads { get; }

        /// <summary>
        /// Starts the thread that operates the V8 engine, which runs in its own thread.
        /// <para>WARNING: You need to use "lock(instance.V8Engine){}" to secure the V8 engine instance if direct access is required from another thread.
        /// That said, however, it's better to use the 'QueueMessage()' method instead whenever possible, or the 'DreamSpaceServer.Globals' property to share data.</para>
        /// </summary>
        void Start();

        /// <summary>
        /// Executes a given line of JavaScript within the current environment, and returns the result for display on a console.
        /// This method wraps the execution in a try-catch block as a precaution, and returns the exception details if an error does occur.
        /// </summary>
        string ExecuteCommand(string lineOfScript);
    }

    public partial class ServerHost<TScriptEngine> : IServerHost<TScriptEngine>
        where TScriptEngine : class, IScriptEngine
    {
        // --------------------------------------------------------------------------------------------------------------------

        [ScriptMember(ScriptMemberSecurity.NoAcccess)]
        public DreamSpaceServer DreamSpaceServer { get; private set; }

        [ScriptMember(ScriptMemberSecurity.NoAcccess)]
        public IScriptEngine ScriptEngine { get; private set; }

        Thread _EngineThread;
        Queue<Message> _Messages;

        [ScriptMember(ScriptMemberSecurity.NoAcccess)]
        public Dictionary<string, Thread> Threads { get; private set; }

        Dictionary<string, List<Action>> _EventCallbacks;

        // --------------------------------------------------------------------------------------------------------------------

        internal ServerHost(DreamSpaceServer dsServer, IScriptEngine scriptEngine = null)
        {
            if (dsServer == null) throw new ArgumentNullException("dsServer");

            DreamSpaceServer = dsServer;

            _Messages = new Queue<Message>();
            _EventCallbacks = new Dictionary<string, List<Action>>();

            if (scriptEngine != null)
            {
                ScriptEngine = scriptEngine;
            }
            else
            {
                if (typeof(TScriptEngine).GetConstructor(Type.EmptyTypes) == null)
                    throw new InvalidOperationException("The type '" + typeof(TScriptEngine).Name + "' must contain a parameterless constructor if no engine instance is given via the 'scriptEngine' parameter.");

                ScriptEngine = Activator.CreateInstance<TScriptEngine>();
            }

            var globals = ScriptEngine.CreateSharedGlobalObject(DreamSpaceServer.Globals);
            ScriptEngine.DefineGlobalProperty("globals", globals);
            ScriptEngine.DefineGlobalProperty("self", this, ScriptMemberSecurity.Permanent);
            //??ScriptEngine.DefineGlobalType<ServerHost<TScriptEngine>>("ServerHost");
            ScriptEngine.DefineGlobalType<MessageType>("MessageType");
        }

        // --------------------------------------------------------------------------------------------------------------------

        /// <summary>
        /// Starts the thread that operates the V8 engine, which runs in its own thread.
        /// <para>WARNING: You need to use "lock(instance.V8Engine){}" to secure the V8 engine instance if direct access is required from another thread.
        /// That said, however, it's better to use the 'QueueMessage()' method instead whenever possible, or the 'DreamSpaceServer.Globals' property to share data.</para>
        /// </summary>
        [ScriptMember(ScriptMemberSecurity.NoAcccess)]
        public void Start()
        {
            _EngineThread = new Thread(_EngineMessageLoop);
            _EngineThread.Start();
        }

        void _EngineMessageLoop()
        {
            while (true)
            {
                if (_Messages.Count > 0)
                {
                    Message msg;

                    lock (_Messages)
                    {
                        msg = _Messages.Dequeue();
                    }

                    try
                    {
                        lock (ScriptEngine)
                        {
                            switch (msg.MessageType)
                            {
                                case MessageType.CallFunction:
                                    if (msg.Data != null && msg.Data.Length > 0)
                                        if (msg.Data[0] is Action)
                                            ((Action)msg.Data[0])();
                                        else if (msg.Data[0] is Action<object>)
                                            ((Action<object>)msg.Data[0])(msg.Data.Length > 1 ? msg.Data[1] : null);
                                    break;

                                case MessageType.SendMessage:
                                    var eventName = (string)msg.Data[0];
                                    List<Action> callbacks;
                                    if (_EventCallbacks.TryGetValue(eventName, out callbacks))
                                        for (var i = 0; i < callbacks.Count; i++)
                                            callbacks[i]();
                                    break;
                            }
                        }
                    }
                    catch { }
                }
                else Thread.Sleep(1);
            }
        }

        // --------------------------------------------------------------------------------------------------------------------

        /// <summary>
        /// Executes a given line of JavaScript within the current environment, and returns the result for display on a console.
        /// This method wraps the execution in a try-catch block as a precaution, and returns the exception details if an error does occur.
        /// </summary>
        [ScriptMember(ScriptMemberSecurity.NoAcccess)]
        public string ExecuteCommand(string lineOfScript)
        {
            lock (ScriptEngine)
            {
                try
                {
                    var result = ScriptEngine.Execute(lineOfScript);
                    return result != null ? result.ToString() : "";
                }
                catch (Exception ex)
                {
                    return ex.GetFullErrorMessage();
                }
            }
        }

        // --------------------------------------------------------------------------------------------------------------------
    }

    // ########################################################################################################################
}
